import os, datetime
from rest_framework import permissions, filters, response, status
from rest_framework.decorators import action
from apps.api.suite.models import SuiteModel
from apps.api.suite.serializers import SuiteModelSerializer, RunTestSuiteModelSerializer
from apps.basic.environment.models import EnvironmentModel
from apps.api.testcase.models import TestCaseModel
from base.settings import YML_FILE_PATH
from utils import viewsets, common
from utils.response import message_response


class SuiteViewSet(viewsets.MyViewSets):
    queryset = SuiteModel.objects.all()
    serializer_class = SuiteModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['create_time']

    @action(methods=["POST"], detail=True)
    def run(self, request, *args, **kwargs):
        suite_obj = self.get_object()
        super().create(request, *args, **kwargs)
        env = EnvironmentModel.objects.filter(id=request.data["env_id"]).filter(is_delete=0).first()
        stamp_path = os.path.join(YML_FILE_PATH, datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S"))
        os.makedirs(stamp_path)
        case_list = eval(suite_obj.cases)
        if len(case_list) == 0:
            message = {"run": "此套件下没有用例，无法运行！"}
            result = message_response(code=1, message=message)
            return response.Response(result, status=status.HTTP_200_OK)
        for case_id in case_list:
            case_obj = TestCaseModel.objects.filter(id=case_id).filter(is_delete=0).first()
            common.assemble_case(stamp_path, env, case_obj)
        return common.run_case(suite_obj.name, stamp_path)

    def get_serializer_class(self):
        if self.action == "run":
            return RunTestSuiteModelSerializer
        else:
            return self.serializer_class

    def perform_create(self, serializer):
        if self.action == "run":
            pass
        else:
            serializer.save()
